package com.lineage.server.utils;

import java.io.Closeable;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class StreamUtil {
  private static final Log _log = LogFactory.getLog(StreamUtil.class);
  
  public static void close(Closeable... closeables) {
    int length = closeables.length;
    int i = 0;
    while (i < length) {
      Closeable c = closeables[i];
      try {
        if (c != null)
          c.close(); 
      } catch (IOException iOException) {}
      i++;
    } 
  }
  
  public static void close(SelectionKey... keys) {
    int length = keys.length;
    int i = 0;
    while (i < length) {
      SelectionKey key = keys[i];
      if (key != null)
        key.cancel(); 
      i++;
    } 
  }
  
  public static void close(Selector... selectors) {
    int length = selectors.length;
    int i = 0;
    while (i < length) {
      Selector selector = selectors[i];
      try {
        if (selector != null)
          selector.close(); 
      } catch (IOException e) {
        _log.error("关闭Selector发生异常", e);
      } 
      i++;
    } 
  }
  
  public static void close(Socket csocket) {
    try {
      if (!csocket.isClosed()) {
        csocket.shutdownInput();
        csocket.shutdownOutput();
        csocket.close();
      } 
    } catch (IOException e) {
      _log.error("关闭Socket发生异常", e);
    } 
  }
  
  public static void close(ServerSocket server) {
    try {
      if (!server.isClosed())
        server.close(); 
    } catch (IOException e) {
      _log.error("关闭ServerSocket发生异常", e);
    } 
  }
  
  public static void interrupt(Thread thread) {
    try {
      if (thread.isAlive())
        thread.interrupt(); 
    } catch (Exception e) {
      _log.error("关闭Thread发生异常", e);
    } 
  }
}
